<template>
  <div class="flex flex-col h-full">
    <!-- formRef.resetFields() -->
    <SearchContainer is-width @search="getData" @reset="onReset">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '70px' } }">
        <a-form-item name="dateRange" label="手术日期" class="w-72 mr-2">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="createDateRange" label="创建日期" class="w-72 mr-2">
          <a-range-picker v-model:value="formState.createDateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="zjm" class="w-64 mr-2">
          <a-input v-model:value="formState.zjm" placeholder="姓名/助记码/卡号/手机号/身份证号" />
        </a-form-item>
        <a-form-item label="手术名称" class="w-64 mr-2" name="ssdm">
          <!-- <a-select
            v-model:value="formState.ssdm"
            placeholder="请选择"
            show-search
            allow-clear
            :options="surgeryOptionList"
            :filter-option="false"
            @search="getSurgery"
          /> -->
          <a-input v-model:value="formState.ssmc" placeholder="请输入手术名称" />
        </a-form-item>
        <a-form-item label="客户来源" class="w-64">
          <SelectCustomerSource v-model:value="formState.khly" multiple max-tag-count="responsive" />
        </a-form-item>
        <a-form-item label="状态" class="w-64">
          <a-select ref="select" v-model:value="formState.statuss" placeholder="请选择" allow-clear mode="multiple">
            <a-select-option :value="0">未登记</a-select-option>
            <a-select-option :value="1">已登记</a-select-option>
            <a-select-option :value="2">已手术</a-select-option>
            <a-select-option :value="3">已作废</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="手术医生" class="w-64" name="aptmOprEmpId">
          <SelectDoctor v-model:value="formState.aptmOprEmpId" :search-type="true" />
        </a-form-item>
        <a-form-item label="业务员" class="w-64">
          <SelectTable v-model:value="formState.brYwyName" type="员工" page-size="999" @select="onSelectEmployee('brYwy', $event)" />
        </a-form-item>
        <a-form-item label="咨询师" class="w-64" name="brZxs">
          <a-select
            v-model:value="formState.brZxs"
            placeholder="请选择"
            show-search
            allow-clear
            :filter-option="false"
            :options="Counselors"
            @search="getCounselors"
          />
        </a-form-item>
        <a-form-item label="负责人" class="w-64">
          <SelectTable v-model:value="formState.brFzrName" type="员工" page-size="999" @select="onSelectEmployee('brFzr', $event)" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2 flex-1">
      <div>
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
          <a-button ref="printViewRegistr" v-print="{ id: 'printViewRegistr' }">打印</a-button>
          <PrintViewRegistr id="printViewRegistr" :print-data="printData" />
          <a-button ref="printViewLabelP" v-print="{ id: 'printViewLabelP' }">打印</a-button>
          <printViewLabel id="printViewLabelP" :print-data="printData" />
        </div>
        <a-button type="primary" class="mb-2 mr-2" @click="onAdd()"> 新增 </a-button>
        <BaseExport type="运维" name="手术登记" code="000049" :search-params="formState">导出</BaseExport>
      </div>
      <BaseTable :loading="loading" column-code="000049" fill :scroll="{ x: 2800 }" :data-source="tableData" bordered :pagination="pagination">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex == 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex == 'statusStr'">
            <a-tag v-if="record.status === '0'" color="blue">{{ record.statusStr }}</a-tag>
            <a-tag v-if="record.status === '1'" color="blue">{{ record.statusStr }}</a-tag>
            <a-tag v-if="record.status === '2'" color="green">{{ record.statusStr }}</a-tag>
            <a-tag v-if="record.status === '4'" color="green">{{ record.statusStr }}</a-tag>
            <a-tag v-if="record.status === '5'" color="green">{{ record.statusStr }}</a-tag>
            <a-tag v-if="record.status === '3'" color="red">{{ record.statusStr }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button type="link" size="small" :disabled="record.status !== '1'" @click="onEdit(record, false)"> 修改 </a-button>
            <a-button type="link" size="small" @click="onPrint(record)"> 腕带 </a-button>
            <template v-if="record.status === '1'">
              <BaseButton confirm-text="确定开始手术?" type="link" size="small" @click="onChangeOperation(record, '4')"> 开始手术 </BaseButton>
            </template>
            <template v-if="record.status === '4'">
              <BaseButton confirm-text="确定结束手术?" type="link" size="small" @click="onChangeOperation(record, '5')"> 结束手术 </BaseButton>
            </template>
            <TableMoreButton>
              <a-button type="link" size="small" @click="onPrintRegister(record)"> 登记单 </a-button>
              <a-button type="link" size="small" @click="onEdit(record, true)"> 手术记录 </a-button>
              <a-button type="link" size="small" @click="onClickBook(record)"> 文书{{ record.ophthDocument }} </a-button>
              <a-button type="link" size="small" @click="onPrintLabel(record)"> 标签 </a-button>
              <BaseButton confirm-text="确定取消登记?" :disabled="record.status !== '1'" danger type="link" size="small" @click="onPrintCancel(record)">
                取消登记
              </BaseButton>
            </TableMoreButton>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <Register v-model:open="editOpen" :row-data="rowData" :edit-type="editType" :recording="recording" @success="onSuccess" />
    <BookUpload v-model:open="bookOpen" :row-data="bookRowData" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import Register from '../components/Register.vue'
import BookUpload from '../components/BookUpload.vue'
import PrintView from './components/PrintView.vue'
import PrintViewRegistr from './components/PrintViewRegistr.vue'
import printViewLabel from './components/printViewLabel.vue'

const surgeryOptionList = ref([])
const rowData = ref({})
const printData = ref({})
const printMe = ref()
const printViewRegistr = ref()
const printViewLabelP = ref()
const bookRowData = ref({})
const editType = ref(false)
const editOpen = ref(false)
const bookOpen = ref(false)
const formRef = ref(null)
const recording = ref(true)
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  // createDateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  createDateRange: [],
  statuss: []
})
const Counselors = ref([])

const onSelectEmployee = (key, select) => {
  formState.value[key + 'Name'] = select.empName
  formState.value[key] = select.empId
}

const onEdit = async (row, state) => {
  editType.value = state
  rowData.value = row
  editOpen.value = true
}
const onAdd = () => {
  recording.value = false
  editType.value = false
  rowData.value = {}
  editOpen.value = true
}
const getCounselors = async (mcbm = '') => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    yxzt: 0,
    mcbm,
    emplbid: '14',
    pageNum: 1,
    pageSize: 9999
  })
  if (code !== 0) return
  Counselors.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
}
const { loading, tableData, pagination, getData } = useTable({
  url: '/operation/opex/getOperationRecordList',
  immediate: true,
  params: formState.value,
  formatParams: (params) => {
    return {
      ...params,
      stdate: params.dateRange?.[0],
      eddate: params.dateRange?.[1],
      createTimeStdate: params.createDateRange?.[0],
      createTimeEddate: params.createDateRange?.[1]
    }
  }
})

const getSurgery = async () => {
  const { code, data } = await post('/common/masterData/getCanUseDrugList', {
    xmlbList: [6]
  })
  if (code !== 0) return
  surgeryOptionList.value = data.map((item) => {
    return {
      label: item.mc,
      value: item.bh
    }
  })
}

// 腕带
const onPrint = async (row) => {
  const { code, msg, data } = await post('/operation/opex/printWristband', { oprLsh: row.lsh })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 登记单
const onPrintRegister = async (row) => {
  const { code, msg, data } = await post('/outp/outPrint/printOperationRecord', { lsh: row.lsh })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      setPrintSize('A5', 'landscape')
      printViewRegistr.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 标签
const onPrintLabel = async (row) => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: row.brId, type: 1, oprLsh: row.oprSn, lsh: row?.lsh })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printViewLabelP.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 取消登记
const onPrintCancel = async (row) => {
  const { code, msg } = await post('/operation/opex/cancellationRegistration', { lsh: row?.lsh })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

// 开始手术
const onChangeOperation = async (row, status) => {
  const { code, msg } = await post('/operation/opex/doRegisterOperation', {
    ...row,
    status: status
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

const onClickBook = (row = {}) => {
  bookOpen.value = true
  bookRowData.value = { ...row }
}

const onSuccess = () => {
  editOpen.value = false
  getData()
}

const onReset = () => {
  formRef.value.resetFields()
  formState.value.brYwyName = ''
  formState.value.brYwy = ''
  formState.value.brFzrName = ''
  formState.value.brFzr = ''
}

onMounted(() => {
  getSurgery()
  getCounselors()
})
</script>
<style lang="less" scoped>
.ant-picker {
  width: 100%;
}
</style>
